package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.article.dto.ArticleDto;
import com.heima.article.dto.ArticleHomeDto;
import com.heima.article.dto.ArticleInfoDto;
import com.heima.article.dto.CollectionBehaviorDto;
import com.heima.article.entity.ApArticle;
import com.heima.article.entity.ApArticleContent;
import com.heima.article.entity.ApAuthor;
import com.heima.article.entity.ApCollection;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.IApArticleContentService;
import com.heima.article.service.IApArticleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.service.IApAuthorService;
import com.heima.article.service.IApCollectionService;
import com.heima.article.task.ArticleTask;
import com.heima.behavior.dto.EntryDto;
import com.heima.behavior.dto.LikesBehaviorDto;
import com.heima.behavior.dto.UnLikesBehaviorDto;
import com.heima.behavior.entity.ApBehaviorEntry;
import com.heima.behavior.entity.ApLikesBehavior;
import com.heima.behavior.entity.ApUnlikesBehavior;
import com.heima.behavior.feign.BehaviorFeign;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.UserThreadLocalUtil;
import com.heima.user.dto.FollowBehaviorDto;
import com.heima.user.entity.ApUserFollow;
import com.heima.user.feign.UserFeign;
import io.seata.core.context.RootContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 文章信息表，存储已发布的文章 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-01-17
 */
@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements IApArticleService {

    @Autowired
    private IApArticleContentService articleContentService;

    @Lazy
    @Autowired
    private ArticleTask articleTask;

    @Autowired
    private StringRedisTemplate redisTemplate;


    /**
     * 保存/更新文章
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult<Long> saveArticle(ArticleDto dto) {
        //1.如果是新增：新增文章，文章内容信息
        //1.1 将入参中文章信息拷贝到PO对象中APArticle
        ApArticle article = new ApArticle();
        BeanUtils.copyProperties(dto, article);
        if (article.getId() == null) {
            //1.2 新增文章记录
            this.save(article);
            //1.3 新增文章内容
            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setArticleId(article.getId());
            apArticleContent.setContent(dto.getContent());
            articleContentService.save(apArticleContent);
        } else {
            //2.如果更新：更新文章，文章内容信息
            //2.1 更新文章信息
            this.updateById(article);
            //2.2 更新文章内容
            LambdaUpdateWrapper<ApArticleContent> updateWrapper = new LambdaUpdateWrapper<>();
            //2.2.1 更新条件  文章ID
            updateWrapper.eq(ApArticleContent::getArticleId, dto.getId());
            //2.2.2 更新字段 文章内容
            updateWrapper.set(ApArticleContent::getContent, dto.getContent());
            //2.2.3 执行更新
            articleContentService.update(updateWrapper);
        }

        //TODO 异步的生成当前文章的静态HTML文件，上传到MINIO中 更新文章静态页字段
        articleTask.createAticleHtmlAndUpload(article.getId());
        return ResponseResult.okResult(article.getId());
    }


    /**
     * APP端首页查询文章分页列表
     *
     * @param dto  查询条件
     * @param type 1：上拉获取更多文章  0：下拉获取最新文章列表
     * @return
     */
    @Override
    public ResponseResult loadArticle(ArticleHomeDto dto, int type) {
        //1.分页参数校验
        if (dto.getSize() <= 0 || dto.getSize() > 50) {
            dto.setSize(20);
        }

        //TODO 目前首页文章列表数据直接查库（不推荐使用） 将来采用redis缓存热点文章数据
        if (dto.getLoaddir() == 1) {
            //前端如果首页:频道为0  其他频道提交频道ID
            String redisKeyPrefix = "leadnews:article:hot:page:";
            String key = redisKeyPrefix + dto.getChannelId();
            int start = 0;
            int end = dto.getSize() - 1;
            Set<String> strings = redisTemplate.opsForZSet().reverseRange(key, start, end);
            if (!CollectionUtils.isEmpty(strings)) {
                //从缓存中获取文章列表，将文章列表返回APP端
                List<ApArticle> apArticleList = strings.stream().map(articleStr -> {
                    ApArticle article = JSON.parseObject(articleStr, ApArticle.class);
                    return article;
                }).collect(Collectors.toList());
                return ResponseResult.okResult(apArticleList);
            }
        }

        //2.封装分页查询条件
        LambdaQueryWrapper<ApArticle> queryWrapper = new LambdaQueryWrapper<>();
        //2.1 文章必须是未删除，未下架
        queryWrapper.eq(ApArticle::getIsDown, false);
        queryWrapper.eq(ApArticle::getIsDelete, false);

        //2.2 设置频道ID查询条件
        if (dto.getChannelId() != null) {
            queryWrapper.eq(ApArticle::getChannelId, dto.getChannelId());
        }

        //2.3 上拉获取更多文章条件
        if (type == 1) {
            //需要判断文章发布时间小于传入最小时间（文章列表最后一篇文章发布时间）
            queryWrapper.lt(ApArticle::getPublishTime, dto.getMinTime());
        } else {
            //2.4 下拉获取最新文章条件
            //需求判断文章发布时间大于传入最大时间（文章列表第一条数据发布时间）
            queryWrapper.gt(ApArticle::getPublishTime, dto.getMaxTime());
        }

        //2.5 根据文章发布时间进行倒序
        queryWrapper.orderByDesc(ApArticle::getPublishTime);

        //3. 执行分页查询
        IPage<ApArticle> page = this.page(new Page<>(1, dto.getSize()), queryWrapper);
        //4.封装响应结果
        return new PageResponseResult(1L, dto.getSize(), page.getTotal(), page.getRecords());
    }


    /**
     * 根据文章ID查询文章信息用于APP端文章详情展示
     *
     * @param dto 文章ID
     * @return {config:{文章信息},content:{文章内容信息}}
     */
    @Override
    public ResponseResult loadArticleInfo(ArticleInfoDto dto) {
        //1.根据入参中文章ID查询文章对象，判断当前文章状态
        ApArticle apArticle = this.getById(dto.getArticleId());
        if (apArticle == null || apArticle.getIsDown() || apArticle.getIsDelete()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //2.根据文章ID查询文章内容信息
        LambdaQueryWrapper<ApArticleContent> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ApArticleContent::getArticleId, dto.getArticleId());
        ApArticleContent content = articleContentService.getOne(queryWrapper);

        //3.按照接口文章封装响应结果
        HashMap<String, Object> mapResult = new HashMap<>();
        mapResult.put("config", apArticle);
        mapResult.put("content", content);
        return ResponseResult.okResult(mapResult);
    }


    @Autowired
    private BehaviorFeign behaviorFeign;

    @Autowired
    private IApCollectionService collectionService;

    @Override
    public ResponseResult collect(CollectionBehaviorDto dto) {
        // 获取当前登录的用户
        User user = UserThreadLocalUtil.get();
        EntryDto entryDto = new EntryDto();
        entryDto.setEquipmentId(dto.getEquipmentId());
        if (user != null) {
            entryDto.setUserId(user.getUserId());
        }
        // 远程查询行为实体
        ResponseResult<ApBehaviorEntry> entryResponseResult = behaviorFeign.getEntry(entryDto);
        if (entryResponseResult != null && entryResponseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
            ApBehaviorEntry entry = entryResponseResult.getData();
            // 构建收藏记录
            ApCollection collection = new ApCollection();
            collection.setEntryId(entry.getId());
            collection.setArticleId(dto.getArticleId());
            collection.setCollectionTime(new Date());
            // 判断是否已经有记录
            LambdaQueryWrapper<ApCollection> query = new LambdaQueryWrapper<>();
            query.eq(ApCollection::getArticleId, dto.getArticleId());
            query.eq(ApCollection::getEntryId, entry.getId());
            ApCollection one = collectionService.getOne(query);
            if (one == null) {
                if (dto.getOperation() == 0) {
                    collectionService.save(collection);
                }
            } else {
                if (dto.getOperation() == 1) {
                    collectionService.removeById(one.getId());
                }
            }
        }
        return ResponseResult.okResult();
    }


    @Autowired
    private IApAuthorService authorService;

    @Autowired
    private UserFeign userFeign;

    @Override
    public ResponseResult loadArticleBehavior(ArticleInfoDto dto) {

        Boolean isFollow = false;
        Boolean isLike = false;
        Boolean isUnLike = false;
        Boolean isCollection = false;

        // 获取当前登录的用户
        User user = UserThreadLocalUtil.get();
        EntryDto entryDto = new EntryDto();
        entryDto.setEquipmentId(dto.getEquipmentId());
        if (user != null) {
            entryDto.setUserId(user.getUserId());
        }
        ResponseResult<ApBehaviorEntry> entryResponseResult = behaviorFeign.getEntry(entryDto);
        if (entryResponseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
            ApBehaviorEntry entry = entryResponseResult.getData();
            // 查询点赞记录
            LikesBehaviorDto likeDto = new LikesBehaviorDto();
            likeDto.setEntryId(entry.getId());
            likeDto.setArticleId(dto.getArticleId());
            ResponseResult<ApLikesBehavior> behaviorResponseResult = behaviorFeign.getLikes(likeDto);
            if (behaviorResponseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
                ApLikesBehavior likesBehavior = behaviorResponseResult.getData();
                if (likesBehavior != null && likesBehavior.getOperation() == 0) {
                    isLike = true;
                }
            }
            // 查询不喜欢记录
            UnLikesBehaviorDto unLikeDto = new UnLikesBehaviorDto();
            unLikeDto.setEntryId(entry.getId());
            unLikeDto.setArticleId(dto.getArticleId());
            ResponseResult<ApUnlikesBehavior> unlikesBehaviorResponseResult = behaviorFeign.getUnlikes(unLikeDto);
            if (unlikesBehaviorResponseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
                ApUnlikesBehavior unlikesBehavior = unlikesBehaviorResponseResult.getData();
                if (unlikesBehavior != null && unlikesBehavior.getType() == 0) {
                    isUnLike = true;
                }
            }

            // 查询收藏记录
            LambdaQueryWrapper<ApCollection> query = new LambdaQueryWrapper<>();
            query.eq(ApCollection::getEntryId, entry.getId());
            query.eq(ApCollection::getArticleId, dto.getArticleId());
            ApCollection collection = collectionService.getOne(query);
            if (collection != null) {
                isCollection = true;
            }
        }

        // 查询作者信息
        ApAuthor apAuthor = authorService.getById(dto.getAuthorId());
        // 查询用户微服务
        FollowBehaviorDto followDto = new FollowBehaviorDto();
        followDto.setUserId(user.getUserId());
        followDto.setFollowId(apAuthor.getUserId());
        ResponseResult<ApUserFollow> followResponseResult = userFeign.getFollow(followDto);
        if (followResponseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
            ApUserFollow userFollow = followResponseResult.getData();
            if (userFollow != null) {
                isFollow = true;
            }
        }


        // 定义返回的结果
        Map<String, Boolean> map = new HashMap<>();
        map.put("isfollow", isFollow);
        map.put("islike", isLike);
        map.put("isunlike", isUnLike);
        map.put("iscollection", isCollection);
        return ResponseResult.okResult(map);
    }

}
